package com.app.project.controller;

import com.app.project.common.BaseResponse;
import com.app.project.common.ErrorCode;
import com.app.project.common.ResultUtils;
import com.app.project.exception.ThrowUtils;
import com.app.project.model.dto.file.ChunkUploadRequest;
import com.app.project.model.dto.file.MergeChunkRequest;
import com.app.project.model.dto.file.UploadFileRequest;
import com.app.project.model.entity.User;
import com.app.project.service.BigFileUploadService;
import com.app.project.service.UserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

/**
 * 大文件上传
 *
 * @author luobin YL526246
 */
@RestController
@RequestMapping("/chunk/file")
public class BigFileUploadController {

    @Resource
    private BigFileUploadService bigFileUploadService;

    @Resource
    UserService  userService;

    /**
     * 检查文件状态(用于断点续传)
     * @param request
     * @return
     */
    @PostMapping("/check/{fileHash}")
    public BaseResponse<Map<String, Object>> checkFileStatus(@PathVariable String fileHash, HttpServletRequest request) {
        ThrowUtils.throwIf(fileHash == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        Map<String, Object> result = bigFileUploadService.checkFileStatus(fileHash, userId);
        return ResultUtils.success(result);
    }

    /**
     * 上传分片文件
     * @param chunkFile
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<Boolean> uploadChunk(@RequestPart("chunk") MultipartFile chunkFile,
                                             @Valid ChunkUploadRequest chunkUploadRequest,
                                             HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();


        Boolean result = bigFileUploadService.uploadChunk(chunkUploadRequest, chunkFile, userId);
        return ResultUtils.success(result);
    }

    /**
     * 合并分片文件
     * @param mergeChunkRequest
     * @param request
     * @return
     */
    @PostMapping("/merge")
    public BaseResponse<String> mergeChunks(@Valid @RequestBody MergeChunkRequest mergeChunkRequest,
                                            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        String result = bigFileUploadService.mergeChunks(mergeChunkRequest, userId);
        ThrowUtils.throwIf(result == null, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

}
